'use strict';

/**
 * @ngdoc function
 * @name jgappApp.controller:AttendanceAddAttendanceCtrl
 * @description
 * # AttendanceAddAttendanceCtrl
 * Controller of the jgappApp
 */
angular.module('jgappApp')
    .controller('AttendanceEdit_location', function ($scope,Util, localStorageService, $timeout, MapService) {
        // 考勤信息
        var attDetail = localStorageService.get("attDetail") || {};
        var vm = this;
        this.ak = MapService.getAk();
        // 设置考勤位置
        this.setCheckPos = function () {
            var endpoint,
                point2 = {};
            if (!vm.previousMarkers[0].marker) {
                return;
            };
            endpoint = vm.previousMarkers[0].marker.getPosition();
            // 设置当前坐标
            attDetail.lat = endpoint.lat
            attDetail.lng = endpoint.lng
            // 获取当前位置信息
            point2.longitude = endpoint.lng;
            point2.latitude = endpoint.lat;
            MapService.getLocation(point2).then(function (data) {
                attDetail.address = data;
                localStorageService.set("attDetail", attDetail);
                Util.goBack();
            });
        };
        // 初始化成功后将map和标记返回以便获取具体位置
        this.finishmap = function (map, previousMarkers) {
            vm.map = map
            vm.previousMarkers = previousMarkers
            setInputAutocomplete();
        };
        // 初始化输入框关联地图
        var setInputAutocomplete = function () {
            //建立一个自动完成的对象
            var ac = new BMap.Autocomplete({
                "input": "suggestId",
                "location": vm.map
            });
            ac.addEventListener("onconfirm", function (e) { //鼠标点击下拉列表后的事件
                var _value = e.item.value;
                var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                MapService.setMarker(vm.map, myValue, vm.mapOptions);
            });
        };
        // 初始化地图
        var initMap = function () {

            // 默认地址坐标
            var point = {
                longitude: 115.863834,
                latitude: 28.68003
            };
            // 如果有坐标信息则显示指定坐标信息,没有坐标信息就获取当前坐标
            if (attDetail.lat) {
                point.latitude = attDetail.lat;
                point.longitude = attDetail.lng
            } else {
                // 获取初始化地址
                MapService.getcurPositon().then(function (data) {
                    vm.mapOptions.center = data;
                    vm.mapOptions.markers[0] = data;
                    $scope.$apply();
                });
            }
            // 初始化地图
            vm.offlineOpts = { retryInterval: 5000 };
            vm.mapOptions = {
                center: point,
                zoom: 17,
                city: "NanChang",
                enableDragging: true,
                markers: [point]
            };
        }
        initMap()
    });
